package br.com.news.database.daos;

import java.util.List;

import javax.inject.Named;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.news.database.daos.interfaces.ICategoriaDao;
import br.com.news.database.entities.CategoriaEntity;
import br.com.news.database.exception.DataBaseException;
import br.com.news.database.utils.GenericDao;

@Named
public class CategoriaDao extends GenericDao<CategoriaEntity, Long> implements ICategoriaDao{

	@Override
	public List<CategoriaEntity> findCategoriaByUsuarioName(String login) throws DataBaseException {
		try {
			return executeQuery("select c from CategoriaEntity c where c.usuario like '%"+login+"%' order by c.idCategoria");
		} catch (DataBaseException e) {
			throw new DataBaseException("Erro ao procurar categoria pelo nome usuario ",e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CategoriaEntity> findCategoriaByStatus(boolean status) throws DataBaseException {
		try {
			Criteria criteria = getSession().createCriteria(CategoriaEntity.class);
			criteria.add(Restrictions.eq("status", status));
			return criteria.list();
		} catch (Exception e) {
			throw new DataBaseException("Erro ao procurar categorias ativas ",e);
		}
	}
	
	@Override
	public List<CategoriaEntity> categoriasMaisAcessadas() throws DataBaseException {
		try {
			return executeQuery("select c from AcessoNoticiaEntity an inner join "
						 +"an.noticia as n inner join "
						 +"n.categoria as c "
						 +"group by c.idCategoria order by count(c.idCategoria) desc");
		} catch (DataBaseException e) {
			throw new DataBaseException("Erro ao procurar categoriasMaisAcessadas ",e);
		}
	}
	
	@Override
	public Long quantidadeCarregadas(Long idCategoria) {
		
		String hql = "select count(an.noticia.idNoticia) from AcessoNoticiaEntity an inner join "
			+" an.noticia n inner join  "
			+" n.categoria as c "
			+" where c.idCategoria =  "+idCategoria 
			+" group by c.idCategoria ";
		
		Query query = getSession().createQuery(hql.toString()); 
		  
  
         return (Long)query.uniqueResult();  
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<CategoriaEntity> findByExample(CategoriaEntity categoria) {
		Criteria criteria = getSession()
		.createCriteria(CategoriaEntity.class);
		
		if (categoria.getDescricao() != null && !categoria.getDescricao().equals("")) {
			criteria.add(Restrictions.like("descricao", categoria.getDescricao(),MatchMode.ANYWHERE));
		}
			criteria.add(Restrictions.eq("status", categoria.isStatus()));
		
		return criteria.list();
	}

}
